package com.shiro.shiroforadmin.controller;

import com.shiro.shiroforadmin.config.TokenConfig;
import com.shiro.shiroforadmin.domain.JsonMsgPojo;
import com.shiro.shiroforadmin.pojo.Admin;
import com.shiro.shiroforadmin.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    //登录
    @PostMapping("login")
    @TokenConfig.PassToken
    public Object login(@Validated({Admin.LoginGroup.class}) Admin loginAdmin, BindingResult bindingResult) {
        JsonMsgPojo j = new JsonMsgPojo();
        if (bindingResult.hasErrors()) {
            bindingResult.getAllErrors().forEach(e -> {
                j.setStatus(3);
                j.setMsg("校验失败：" + e.getDefaultMessage());
            });
            return j;
        }
        return adminService.login(loginAdmin);
    }

//    注册
    @PostMapping("register")
    @TokenConfig.UserLoginToken
    @TokenConfig.UserLoginTokenAndPerm(perm = "注册")
    public Object register(Admin admin) {
        return adminService.register(admin);
    }



    //修改账号名称
    @PostMapping("editUsername")
    @TokenConfig.UserLoginToken
    @TokenConfig.UserLoginTokenAndPerm(role={"院长","校长"}, perm = "修改")
    public Object editUsername(@Validated({Admin.UpdateUsernameGroup.class}) Admin adminNew, BindingResult bindingResult) {
        JsonMsgPojo j = new JsonMsgPojo();
        if (bindingResult.hasErrors()) {
            bindingResult.getAllErrors().forEach(e -> {
                j.setStatus(3);
                j.setMsg("校验失败：" +e.getDefaultMessage());
            });
            return j;
        }
        return adminService.editUsername(adminNew);
    }


    //修改密码
    @PostMapping("editPassword")
    @TokenConfig.UserLoginToken
    @TokenConfig.UserLoginTokenAndPerm(perm = "修改")
    public Object editPassword(@Validated({Admin.UpdatePasswordGroup.class}) Admin adminNew, String passwordConfig, BindingResult bindingResult) {
        JsonMsgPojo j = new JsonMsgPojo();
        if (bindingResult.hasErrors()) {
            bindingResult.getAllErrors().forEach(e -> {
                j.setStatus(3);
                j.setMsg("校验失败：" +e.getDefaultMessage());
            });
            return j;
        }
        return adminService.editPassword(adminNew,passwordConfig);
    }

//    删除账户
    @GetMapping("delete")
    @TokenConfig.UserLoginToken
    @TokenConfig.UserLoginTokenAndPerm(role={"院长","校长"}, perm = "删除")
    public Object delete(Integer id){
        return adminService.delete(id);
    }

}
